package com.test.zuul;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author:fangn
 * @Date:2019/11/7
 **/
@Component
public class MyFilter extends ZuulFilter {
    private static Logger LOGGER = LoggerFactory.getLogger(MyFilter.class);

    @Override
    public String filterType() {
        LOGGER.info("pre");
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        LOGGER.info("{} >>> {}", request.getMethod(), request.getRequestURI());
        String token = request.getParameter("token");
        if (token == null) {
            LOGGER.warn("token is null");
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(401);
            try {
                currentContext.getResponse().getWriter().write("token is null");
            } catch (IOException e) {
                LOGGER.error("error:",e);
            }
            return null;
        }
        LOGGER.info("token is ok");
        return null;
    }
}
